package com.my.study.net;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Carlos
 * @version 1.0
 * @Description TODO
 * @date 2021/7/3 21:16
 **/
@Slf4j(topic = "c.SocketTCP03Server")
public class SocketTCP03Server {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);
        log.debug("服务端，在9999端口监听，等待连接...");
        // 当没有客户端连接9999端口时，程序就会在此阻塞
        Socket socket = serverSocket.accept();
        log.debug("服务端 socket = {}", socket.getClass());

        //===============================================读取客户端发送的消息
        // 转换：字节 -> 字符
        InputStream in = socket.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String context = reader.readLine();
        log.debug("context: {}", context);


        //===============================================向客户端发送消息
        OutputStream out = socket.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
        writer.write("Hello client 字符流");
        writer.newLine();
        writer.flush();



        // 关闭流，如果流被包装或者转换了，关闭最外层的流即可
        writer.close();
        reader.close();
        socket.close();
        serverSocket.close();
    }

}
